package cn.tedu.sp06.fb;

import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class ItemFB implements FallbackProvider {
    @Override
    public String getRoute() {
        /*
        返回一个service-id如下,表示当前降级类是针对指定的这个后台服务的降级类
        返回一个*号,表示对所有服务都应用这个配置类
        返回null,等同于*
         */
        return "item-service";
    }
        /*
        这是发回给客户端的降级相应
         */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException { //getStatusCode封装了状态对象 包含了状态码和状态文本信息
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            @Override
            public int getRawStatusCode() throws IOException { //getRawStatusCode里面封装了状态码
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }

            @Override
            public String getStatusText() throws IOException { //getStatusText里面封装了状态文本信息
                return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String json= JsonResult.err().code(500).msg("出错").toString();
                new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
                return null;
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders h= new HttpHeaders();
                h.add("Content-Type","application/json;charset=UTF-8");
                return h;
            }
        };
    }
}
